<script setup lang="tsx">
import { ElButton, ElPopconfirm, ElSwitch, ElTag } from 'element-plus';
import { fetchGetUserList } from '@/service/api';
import { $t } from '@/locales';
import { enableStatusRecord, userGenderRecord } from '@/constants/business';
import OperateDrawer from './modules/operate-drawer.vue';
import RoleOperate from './modules/role-operate.vue';
import Search from './modules/search.vue';
import { ApiUserQuery, ApiUserOut, UserApi, ApiStateInput } from '@/api-services';
import { feature, getAPI } from '@/axios-utils';
import { fetchTableQuery, useNetoTable, useTableOperate } from '@/hooks/common/neto-table';
import { ref, watch } from 'vue';
import { queryDone } from '@/utils/api';

defineOptions({ name: 'UserManage' });

// 定义 apiFunc 为一个函数，接受参数并返回 Promise
const apiFunc = (params: ApiUserQuery) =>
  fetchTableQuery<ApiUserQuery, ApiUserOut>(params, (internalParams: ApiUserQuery) =>
    getAPI(UserApi).getPagedList(internalParams)
  );


const loadingStates = ref<Record<string, boolean>>({});
const {
  columns,
  columnChecks,
  data,
  loading,
  getData,
  getDataByPage,
  mobilePagination,
  searchParams,
  resetSearchParams
} = useNetoTable({
  apiFn: apiFunc,
  showTotal: true,
  apiParams: {
    pageIndex: 1,
    pageSize: 10,
    isEnable: undefined,
    userType: undefined,
    keyWords: undefined,
    startTime: null,
    endTime: null
  },
  columns: () => [
    { type: 'selection', width: 48 },
    {
      prop: 'account',
      label: $t('page.manage.user.userName'),
      minWidth: 100
    },
    {
      //'账号类型'
      prop: 'userType',
      label: $t('page.manage.user.userType'),
      align: 'center',
      minWidth: 100,
      formatter: record => {
        if (record.userType === null) {
          return '';
        }

        const tagMap: Record<number, string> = {
          0: $t('page.manage.user.userTypeEnum.default'),
          100: $t('page.manage.user.userTypeEnum.admin'),
          101: $t('page.manage.user.userTypeEnum.superAdmin'),
          102: $t('page.manage.user.userTypeEnum.developer')
        };

        switch (record.userType) {
          case 0:
            return <ElTag type="primary">{tagMap[record.userType]}</ElTag>;
          case 100:
            return <ElTag type="success">{tagMap[record.userType]}</ElTag>;
          case 101:
            return <ElTag type="danger">{tagMap[record.userType]}</ElTag>;
          case 102:
            return <ElTag type="warning">{tagMap[record.userType]}</ElTag>;
          default:
            return '';
        }
      }
    },
    {
      //角色
      prop: 'roleName',
      label: $t('page.manage.user.userRole'),
      align: 'center',
      minWidth: 100
    },
    {
      //昵称
      prop: 'nick',
      label: $t('page.manage.user.nickName'),
      align: 'center',
      minWidth: 100
    },
    {
      //邮箱
      prop: 'email',
      label: $t('page.manage.user.userEmail'),
      align: 'center',
      minWidth: 200
    },
    {
      //手机号
      prop: 'phone',
      label: $t('page.manage.user.userPhone'),
      align: 'center',
      minWidth: 100
    },
    // 是否启用
    {
      prop: 'isEnable',
      label: $t('page.manage.common.isEnable'),
      align: 'center',
      minWidth: 100,
      formatter: record => {
        if (record.isEnable === null) {
          return '';
        }
        const handleSwitchChange = async (checked: boolean | string | number) => {
          const model: ApiStateInput = {
            id: record.id,
            state: Boolean(checked),
            field: 'IsEnable'
          };
          // 提交请求
          loadingStates.value = {
            ...loadingStates.value,
            [record.id!]: true
          };
          const [err, res] = await feature(getAPI(UserApi).setState(model));
          loadingStates.value = {
            ...loadingStates.value,
            [record.id!]: false
          };
          queryDone(err, async () => {
            if (res?.data.data) {
              record.isEnable = Boolean(checked);
            } else {
              window.$message?.error($t('common.failed'));
            }
          });
        };
        return (
          <ElSwitch
            v-model={record.isEnable}
            onChange={handleSwitchChange}
            loading={loadingStates.value[record.id!] || false}
          ></ElSwitch>
        );
      }
    },
    {
      //省份
      prop: 'province',
      label: $t('page.manage.user.province'),
      align: 'center',
      hide: true,
      minWidth: 100
    },
    {
      //城市
      prop: 'city',
      label: $t('page.manage.user.city'),
      align: 'center',
      hide: true,
      minWidth: 100
    },
    {
      //镇
      prop: 'town',
      label: $t('page.manage.user.town'),
      align: 'center',
      hide: true,
      minWidth: 100
    },
    {
      //详细地址
      prop: 'address',
      label: $t('page.manage.user.address'),
      align: 'center',
      hide: true,
      minWidth: 100
    },
    {
      //备注
      prop: 'remark',
      //dataIndex: 'remark',
      label: $t('page.manage.user.remark'),
      align: 'center',
      minWidth: 100
    },
    {
      //创建时间
      prop: 'creationTime',
      label: $t('common.creationTime'),
      align: 'center',
      hide: true,
      minWidth: 150
    },
    {
      //创建人
      prop: 'creatorUserName',
      label: $t('common.creatorUserName'),
      align: 'center',
      hide: true,
      minWidth: 200
    },
    {
      //修改时间
      prop: 'updateTime',
      label: $t('common.updateTime'),
      align: 'center',
      hide: true,
      minWidth: 150
    },
    {
      //修改人
      prop: 'updateUserName',
      label: $t('common.updateUserName'),
      align: 'center',
      hide: true,
      minWidth: 100
    },
    {
      //最后登录时间
      prop: 'lastLoginTime',
      label: $t('page.manage.user.lastLoginTime'),
      align: 'center',
      minWidth: 150
    },

    {
      //最后登录Ip
      prop: 'lastLoginIp',
      label: $t('page.manage.user.lastLoginIp'),
      align: 'center',
      minWidth: 100
    },
    {
      prop: 'operate',
      label: $t('common.operate'),
      align: 'center',
      fixed: 'right',
      minWidth: 200,
      formatter: row => (
        <div class="flex-center">
          <ElButton type="primary" plain size="small" onClick={() => edit(row.id!)}>
            {$t('common.edit')}
          </ElButton>

          <ElButton type="primary" plain size="small" onClick={() => editUserRole(row.id!)}>
            {$t('common.userRole.edit')}
          </ElButton>
          <ElPopconfirm title={$t('common.confirmDelete')} onConfirm={() => handleDelete(row.id!)}>
            {{
              reference: () => (
                <ElButton type="danger" plain size="small">
                  {$t('common.delete')}
                </ElButton>
              )
            }}
          </ElPopconfirm>
        </div>
      )
    }
  ]
});

const {
  isVisible,
  operateType,
  editingData,
  getEditData,
  handleAdd,
  handleEdit,
  checkedRowKeys,
  onBatchDeleted,
  onDeleted
  // closeDrawer
} = useTableOperate(data, getData);


async function handleBatchDelete() {
  // eslint-disable-next-line no-console
  console.log(checkedRowKeys.value);
  // request
  //将id转换为number
  const ids = checkedRowKeys.value.map(it => Number(it));
  if (!ids) {
    return;
  }
  // 提交请求
  const [err, res] = await feature(getAPI(UserApi).batchDelete(ids));

  queryDone(err, async () => {
    if (res?.data.data) {
      onBatchDeleted();
    } else {
      // 失败
      window.$message?.error($t('common.failed'));
    }
  });
}

function handleDelete(id: number) {
  // eslint-disable-next-line no-console
  console.log(id);
  // request

  onDeleted();
}

const isVisibleRole = ref(false);
const editUserRole = (id: number) => {
  getEditData(id);
  isVisibleRole.value = true;
};
function edit(id: number) {
  handleEdit(id);
}
</script>

<template>
  <div class="min-h-500px flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <Search v-model:model="searchParams" @reset="resetSearchParams" @search="getDataByPage" />
    <ElCard class="sm:flex-1-hidden card-wrapper" body-class="ht50">
      <template #header>
        <div class="flex items-center justify-between">
          <p>{{ $t('page.manage.user.title') }}</p>
          <TableHeaderOperation v-model:columns="columnChecks" :disabled-delete="checkedRowKeys.length === 0"
            :loading="loading" @add="handleAdd" @delete="handleBatchDelete" @refresh="getData" />
        </div>
      </template>
      <div class="h-[calc(100%-50px)]">
        <ElTable v-loading="loading" height="100%" border class="sm:h-full" :data="data" row-key="id"
          @selection-change="checkedRowKeys = $event">
          <ElTableColumn v-for="col in columns" :key="col.prop" v-bind="col" />
        </ElTable>
      </div>
      <div class="mt-20px flex justify-end">
        <ElPagination v-if="mobilePagination.total" layout="total,prev,pager,next,sizes" v-bind="mobilePagination"
          v-model:current-page="mobilePagination.currentPage" v-model:page-size="mobilePagination.pageSize" />
      </div>

      <OperateDrawer v-model:visible="isVisible" :operate-type="operateType" :row-data="editingData"
        @submitted="getDataByPage" />
      <RoleOperate v-model:visible="isVisibleRole" :row-data="editingData"></RoleOperate>
    </ElCard>
  </div>
</template>

<style lang="scss" scoped>
:deep(.el-card) {
  .ht50 {
    height: calc(100% - 50px);
  }
}
</style>
